package com.wusuowei.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @description web安全配置
 * @author LGY
 * @date 2023/03/31 00:24
 * @version 1.0.0
 */
@Configuration
@EnableWebSecurity //开启Security
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启spring方法级别安全
@Order(-1) //Bean的执行顺序的优先级
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//    @Autowired
//    private GatewayAuthFilter gatewayAuthFilter;


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * @description 身份验证管理器（为了自定义校验用户身份）
     * @return {@link AuthenticationManager }
     * @author LGY
     * @date 2023/03/31 16:20
     */
    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().antMatchers(HttpMethod.OPTIONS, "/oauth/**");//放行/oauth/**的预检请求，不然有跨域问题;
    // session禁用配置
        http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) ; // 无状态
        // 处理异常
//        http.exceptionHandling()
//                .accessDeniedHandler(new MyAccessDeniedHandler())
//                .authenticationEntryPoint(new MyAuthenticationEntryPoint());

        http.authorizeRequests()
                //无需认证的为static下的静态资源，以及/index请求
                .antMatchers("/static/**","/index").permitAll()
                //其它所有请求都需要进行验证
                .anyRequest().authenticated();
    }



}
